<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="orderRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="1000"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="drawer-order">
      <a-form
        ref="formRef"
        :colon="false"
        autocomplete="off"
        :label-col="{ style: { width: '90px' } }"
        :model="formState"
        :rules="getFormRules"
        lableWidth
      >
        <div class="box-form">
          <a-form-item label="订单属性" name="tryFlag" required>
            <template v-if="drawerInfo.type === operateActionType.ADD">
              <a-radio-group v-model:value="formState.tryFlag" @change="tryChange">
                <a-radio :value="2">正式</a-radio>
                <a-radio :value="1">试用</a-radio>
              </a-radio-group>
              <template v-if="formState.tryFlag == 1">
                <a-input-number
                  v-model:value="formState.days"
                  :min="1"
                  :max="30"
                  class="none-handle"
                  :precision="0"
                  placeholder="天数"
                  :value-style="{ color: '#192235', fontWeight: '600', fontSize: '14px' }"
                  style="width: 150px; margin-right: 4px"
                />
                <span>天</span>
              </template>
            </template>
            <!-- todo 暂时只有正式 -->
            <div v-else class="form-value">正式</div>
          </a-form-item>
          <a-form-item label="开通企业" name="userTenantId">
            <template v-if="drawerInfo.type === operateActionType.ADD">
              <a-select
                v-model:value="formState.userTenantId"
                allowClear
                show-search
                :filter-option="filterOption"
                placeholder="请选择开通企业"
                @change="handleSelectedEnterprise"
                :options="drawerInfo.enterpriseSubList"
                :field-names="{
                  label: 'orgName',
                  value: 'tenantId',
                  children: 'children'
                }"
              ></a-select>
            </template>

            <div v-else class="form-value">{{ drawerInfo.record.enterprise }}</div>
          </a-form-item>
          <a-form-item label="开通套餐" name="packageCode">
            <template v-if="drawerInfo.type === operateActionType.ADD">
              <a-select
                v-model:value="packageType"
                placeholder="请选择开通套餐"
                :options="packageTypeList"
                @change="changePackageType"
                :disabled="!formState.userTenantId || formState.tryFlag == 1"
              ></a-select>
            </template>
            <div v-else class="form-value">{{ drawerInfo.record.packageName }}</div>
          </a-form-item>
          <div class="package-container" v-if="funPackageList.length && packageType === 1 && formState.userTenantId">
            <div
              class="package-item"
              :class="{
                selected: isSelected(item.packageCode),
                'item-disabled': !item.buyTryFlag && formState.tryFlag == 1
              }"
              v-for="item in funPackageList"
              @click.prevent="selectPackage(item)"
              :key="item.packageCode"
            >
              <span class="package-name">{{ item.packageName }}</span>
              <div class="package-unitprice">￥{{ item.channelUnitPrice }}</div>
            </div>
          </div>
          <div
            class="package-container"
            v-if="quantityPackageList.length && packageType === 2 && formState.userTenantId"
          >
            <div
              class="package-item"
              v-for="item in quantityPackageList"
              :key="item.packageCode"
              @click.prevent="selectPackage(item)"
              :class="{ selected: formState.packageCode[0] === item.packageCode }"
            >
              <span class="package-name">{{ item.packageName }}</span>
              <div class="package-unitprice">￥{{ item.channelUnitPrice }}</div>
            </div>
          </div>
          <!-- @change="packageHandleChange" -->
          <a-form-item label="购买数量" name="quantity" v-if="packageType === 2">
            <a-input-number
              style="width: 150px"
              v-if="drawerInfo.type === operateActionType.ADD"
              :precision="0"
              v-model:value="formState.quantity"
              :min="1"
              :max="2147483647"
            />
            <div v-else class="form-value">{{ drawerInfo.record.quantity }}个</div>
          </a-form-item>
          <template v-if="formState.tryFlag == 2">
            <a-form-item label="订单金额" name="orderAmt">
              <div class="order-amount">
                <a-statistic
                  v-if="drawerInfo.type === operateActionType.EDIT"
                  :value="drawerInfo.record.orderAmt"
                  :precision="2"
                  :value-style="{ color: '#192235', fontWeight: '600', fontSize: '14px' }"
                />
                <a-input-number
                  v-else
                  style="width: 150px"
                  :precision="0"
                  v-model:value="formState.orderAmt"
                  class="none-handle"
                  placeholder="输入订单金额"
                  :value-style="{ color: '#192235', fontWeight: '600', fontSize: '14px' }"
                  :min="1"
                  :max="2147483647"
                />
              </div>
            </a-form-item>
            <a-form-item label="结算价格" name="channelBasePrice" v-if="drawerInfo.type === operateActionType.ADD">
              <a-statistic
                :value="channelBasePrice"
                :precision="2"
                :value-style="{ color: '#192235', fontWeight: '600', fontSize: '14px' }"
              />
            </a-form-item>
          </template>
          <template v-else>
            <a-form-item label="订单金额">
              <a-statistic
                :value="0"
                :precision="2"
                :value-style="{ color: '#192235', fontWeight: '600', fontSize: '14px' }"
              />
            </a-form-item>
            <a-form-item label="结算价格" name="channelBasePrice">
              <a-statistic
                :value="0"
                :precision="2"
                :value-style="{ color: '#192235', fontWeight: '600', fontSize: '14px' }"
              />
            </a-form-item>
          </template>

          <a-form-item label="付款状态" name="orderStatus">
            <a-radio-group v-model:value="formState.orderStatus" :disabled="formState.tryFlag == 1">
              <a-radio :value="1">待付款</a-radio>
              <a-radio :value="2">已付款</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="是否真实收费" name="realReceiveAmt" required>
            <a-radio-group
              v-model:value="formState.realReceiveAmt"
              @change="() => (realOrderAmt = null)"
              :disabled="formState.tryFlag == 1"
            >
              <a-radio :value="1">否</a-radio>
              <a-radio :value="2">是</a-radio>
            </a-radio-group>
            <a-input-number
              v-if="formState.realReceiveAmt === 2"
              id="inputNumber"
              v-model:value="realOrderAmt"
              :min="1"
              :max="2147483647"
              class="none-handle"
              :precision="0"
              :disabled="formState.realReceiveAmt === 1"
              placeholder="输入真实收到费用"
              :value-style="{ color: '#192235', fontWeight: '600', fontSize: '14px' }"
              style="width: 150px"
            />
          </a-form-item>
          <a-form-item label="备注" name="remark">
            <a-textarea
              allowClear
              :maxLength="100"
              :autoSize="{ minRows: 3, maxRows: 3 }"
              placeholder="请输入备注信息"
              v-model:value.trim="formState.remark"
            >
            </a-textarea>
          </a-form-item>
        </div>
        <!-- <div class="detail-upload">
          <a-form-item label="上传附件" name="attachmentKey">
            <UploadFile v-model="formState.attachmentKey" fileType="3" />
            <div class="upload-info">
              <info-circle-outlined class="info-icon" />
              只支持jpg、png格式，不超过10M
            </div>
          </a-form-item>
        </div> -->
      </a-form>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { operateActionType } from '@/types/enum'
import { numTransString, scrollToFirstError } from '@/utils'
import EllipsisTooltip from '@/components/EllipsisTooltip/index.vue'
import { message } from 'ant-design-vue'
import { InfoCircleOutlined, CloseCircleFilled } from '@ant-design/icons-vue'
import UploadFile from '@/components/UploadFile/index.vue'
import { cloneDeep, debounce } from 'lodash-es'
import api from '@/api'

const {
  enterpriseList,
  queryOrderPackageList,
  subEnterpriseList,
  orderAdd,
  orderEdit,
  orderDetail,
  qureyEnterpriseList,
  queryTrialDetail
} = api

const emit = defineEmits(['operateSuccess', 'register'])

const drawerInfo = reactive<any>({
  type: '',
  record: {},
  enterpriseList: [], //租户列表
  enterpriseSubList: [], //下级企业列表
  packageList: []
})

const unitPrice = ref(0) // 标准价格
const channelUnitPrice = ref(0) //渠道售价
const channelBasePrice = ref(0) //结算价格
const packageType = ref(1) // 套餐类型
const realOrderAmt = ref(null) //真实收费
const fetching = ref(false)
const formRef = ref()
const tryToFormal = ref(false)
const funPackageList = ref<any>([]) //功能套餐列表
const quantityPackageList = ref<any>([]) //数量套餐列表
const packageTypeList = [
  {
    label: '按周期计费',
    value: 1
  },
  {
    label: '按数量计费',
    value: 2
  }
]
const formState = reactive<any>({
  tryFlag: 2,
  days: 30,
  buyerTenantId: null, // 租户ID
  packageCode: [], // 套餐代码
  realReceiveAmt: 1, //是否真实收到费用
  // userTenantIds: [], // 租户列表
  userTenantId: null, // 单个租户
  quantity: 1, // 购买数量
  attachmentKey: '', // 附件key
  remark: '', // 备注
  orderStatus: 1, // 订单状态 1-待付款,2-已完成,3-已关闭
  orderAmt: null //订单金额
})
const getFormRules = {
  packageCode: [{ required: true, message: '请选择开通套餐', trigger: 'blur' }],
  userTenantId: [{ required: true, message: '请选择开通企业', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入购买数量', trigger: 'blur' }],
  orderStatus: [{ required: true, message: '请选择付款状态', trigger: 'change' }],
  orderAmt: [{ required: true, message: '请输入订单金额', trigger: 'blur' }]
}
watch(
  () => formState.userTenantId,
  (val) => {
    if (!val) {
      unref(formRef).clearValidate(['packageCode'])
    }
  }
)
const setFormState = (record: any) => {
  formState.buyerTenantId = record.buyerTenantId || null
  formState.packageCode = record.packageCode || []
  formState.userTenantId = record.userTenantId || null
  formState.quantity = record.quantity || 1
  formState.attachmentKey = record.attachmentKey || ''
  formState.remark = record.remark || ''
  formState.orderStatus = record.orderStatus || 1
  formState.orderAmt = record.orderAmt || 0
}

const [orderRegister, { closeDrawer, changeOkLoading, changeLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  drawerInfo.record = cloneDeep(data.record) || {}
  if (data.tryToFormal) {
    tryToFormal.value = data.tryToFormal
  }
  try {
    changeLoading(true)
    // let packageRes = await queryOrderPackageList({
    //   packageStatus: 1
    // })
    // drawerInfo.packageList = packageRes.result || []
    if (drawerInfo.type !== operateActionType.ADD) {
      let orderRes = await orderDetail({ orderNo: drawerInfo.record.orderNo })
      drawerInfo.record = cloneDeep(orderRes.result) || {}
      drawerInfo.record.packageName = data.record.packageName || ''
      packageType.value = drawerInfo.record.packageType || 1
      if (data.record.realOrderAmt) {
        formState.realReceiveAmt = 2
        realOrderAmt.value = data.record.realOrderAmt
      }
      setFormState(drawerInfo.record)
    } else {
      let res = await qureyEnterpriseList()
      drawerInfo.enterpriseSubList = res.result
      let copyRes: any = {}
      if (tryToFormal.value) {
        copyRes = await queryTrialDetail({ orderNo: drawerInfo.record.orderNo })
        let copyInfo = copyRes.result
        copyOrder(copyInfo)
      }
    }
    changeLoading(false)
  } catch (error) {
    changeLoading(false)
  }
})

const drawerReset = () => {
  changeOkLoading(false)
  unref(formRef).resetFields()
  realOrderAmt.value = null
  unitPrice.value = 0
  formState.packageCode = []
  channelBasePrice.value = 0
  channelUnitPrice.value = 0
  packageType.value = 1
  formState.days = 30
  formState.userTenantId = null
  funPackageList.value = []
  quantityPackageList.value = []
  tryToFormal.value = false
}
const changePackageType = () => {
  realOrderAmt.value = null
  formState.orderAmt = null
  unitPrice.value = 0
  formState.quantity = 1
  formState.packageCode = []
  channelBasePrice.value = 0
  channelUnitPrice.value = 0
}
// 订单金额
const orderMoney = computed(() => {
  let money = 0
  let baseMoney = 0
  if (packageType.value === 1) {
    funPackageList.value.forEach((packageItem: any) => {
      if (formState.packageCode.includes(packageItem.packageCode)) {
        money += packageItem.channelUnitPrice
        baseMoney += packageItem.channelBasePrice
      }
    })
  }
  if (packageType.value === 2) {
    let selectPackageNum = quantityPackageList.value.find((item: any) => {
      return item.packageCode === formState.packageCode[0]
    })
    if (selectPackageNum) {
      baseMoney = selectPackageNum.channelBasePrice * formState.quantity
      money = selectPackageNum.channelUnitPrice * formState.quantity
    }
  }
  channelBasePrice.value = baseMoney
  return money || null
})
// 监听智能选择的套餐，改变金额
watch(orderMoney, (val: any) => {
  formState.orderAmt = val
})

// 选择企业名称获取套餐
const handleSelectedEnterprise = async (val: string, option: any) => {
  formState.packageCode = []
  formState.orderAmt = null
  unitPrice.value = 0
  channelBasePrice.value = 0
  channelUnitPrice.value = 0
  packageType.value = 1
  realOrderAmt.value = null
  formState.realReceiveAmt = 1
  console.log(val, option)

  if (val && option.topTenantId) {
    formState.buyerTenantId = option.topTenantId
    let packageRes = await queryOrderPackageList({
      orgTenantId: option.tenantId,
      packageStatus: 1
    })
    drawerInfo.packageList = packageRes.result || []
    funPackageList.value = packageRes.result.filter((item: any) => {
      return item.packageType === 1
    })
    quantityPackageList.value = packageRes.result.filter((item: any) => {
      return item.packageType === 2
    })
    console.log('功能套餐======>', funPackageList)
    console.log('数量套餐======>', quantityPackageList)
  }
}

// 订单属性切换
const tryChange = () => {
  formState.userTenantId = null // 清除所选公司
  packageType.value = 1
  formState.packageCode = []
  formState.orderStatus = 2
  formState.realReceiveAmt = 1
  realOrderAmt.value = null
}

// 选择套餐
const selectPackage = (item: any) => {
  console.log('item===>', item)

  if (formState.tryFlag == 1 && !item.buyTryFlag) {
    return
  }
  if (packageType.value === 1) {
    let index = formState.packageCode.indexOf(item.packageCode)
    if (index !== -1) {
      formState.packageCode.splice(index, 1)
    } else {
      formState.packageCode.push(item.packageCode)
    }
  } else {
    formState.packageCode = [item.packageCode]
  }
  if (formState.packageCode.length && formState.packageCode.length) {
    unref(formRef).clearValidate(['packageCode'])
  }
}
const isSelected = (packageCode: any) => {
  return formState.packageCode.includes(packageCode)
}

const filterOption = (input: string, option: any) => {
  return option.orgName && option.orgName.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
// 复制订单
const copyOrder = async (order: any) => {
  formState.tryFlag = order.tryFlag
  formState.userTenantId = order.userTenantId
  console.log('企业列表====>', drawerInfo.enterpriseSubList)
  let selectTenant = drawerInfo.enterpriseSubList.find((item: any) => {
    return item.tenantId === order.userTenantId
  })

  console.log('选中的企业选项====>', selectTenant)
  await handleSelectedEnterprise(order.userTenantId, selectTenant)
  packageType.value = order.packageType
  changePackageType()
  let selectedPackage: any = []
  if (order.packageType === 1) {
    selectedPackage = funPackageList.value.filter((item: any) => {
      return order.packageCodeSet.includes(item.packageCode)
    })
  } else {
    selectedPackage = quantityPackageList.value.filter((item: any) => {
      return order.packageCodeSet.includes(item.packageCode)
    })
  }
  console.log('复制的套餐====>', selectedPackage)
  await selectedPackage.forEach((item: any) => {
    selectPackage(item)
  })
  // formState.orderAmt = order.orderAmt
  formState.quantity = order.quantity || 1
  formState.orderStatus = order.orderStatus || 1
  formState.remark = order.remark || ''
  if (order.realOrderAmt) {
    formState.realReceiveAmt = 2
  }
  realOrderAmt.value = order.realOrderAmt
}
// 提交数据
const confirmSubmit = async () => {
  try {
    if (drawerInfo.type === operateActionType.ADD) {
      if (formState.tryFlag === 1 && !formState.days) {
        message.error('请填写试用天数')
        return
      }
      await unref(formRef).validate()
      if (formState.realReceiveAmt === 2 && !realOrderAmt.value) {
        message.error('请填写真实收到的费用')
        return
      }
      changeOkLoading(true)

      let reqData: any = {
        buyerTenantId: formState.buyerTenantId,
        packageCodeSet: formState.packageCode,
        attachmentKey: formState.attachmentKey,
        orderStatus: formState.orderStatus,
        remark: formState.remark,
        tryFlag: formState.tryFlag,
        days: formState.tryFlag == 1 ? formState.days : '',
        orderAmt: formState.tryFlag == 1 ? 0 : Number(formState.orderAmt),
        realOrderAmt: formState.realReceiveAmt === 1 ? '' : Number(realOrderAmt.value)
      }
      if (packageType.value === 1) {
        reqData.userTenantIds = [formState.userTenantId]
      } else if (packageType.value === 2) {
        reqData.userTenantIds = [formState.userTenantId]
        reqData.quantity = formState.quantity
      }

      await orderAdd({
        ...reqData
      })
    } else if (drawerInfo.type === operateActionType.EDIT) {
      changeOkLoading(true)
      await orderEdit({
        orderNo: drawerInfo.record.orderNo,
        attachmentKey: formState.attachmentKey,
        remark: formState.remark,
        orderStatus: formState.orderStatus,
        realOrderAmt: formState.realReceiveAmt === 1 ? '' : Number(realOrderAmt.value)
      })
    }
    message.success(drawerInfo.type === operateActionType.ADD ? '订单新增成功' : '订单编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
  }
}
</script>

<style lang="less" scoped>
.drawer-order {
  padding: 40px 24px 24px;
  .box-form {
    width: 580px;
    padding-left: 60px;

    .order-amount {
      font-size: 14px;
      color: #192235;
    }
    .form-value {
      color: #192235;
      font-size: 14px;
      line-height: 32px;
    }
  }
  .package-container {
    margin-left: 88px;
    margin-bottom: 24px;
    max-height: 410px;
    overflow: auto;
    background: #fafafa;
    border-radius: 4px;
    width: 664px;
    padding: 8px 12px 16px 16px;
    display: flex;
    flex-wrap: wrap;
    .package-item {
      width: 152px;
      height: 69px;
      margin-right: 4px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid #cdcdcd;
      margin-top: 8px;
      padding: 8px 16px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .package-name {
        width: 100%;
        font-size: 12px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        color: #192235;
        line-height: 14px;
        word-break: break-all;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2; /* 这里是超出几行省略 */
        overflow: hidden;
      }
      .package-unitprice {
        height: 22px;
        width: 100%;
        font-weight: 500;
        color: #d9001d;
        font-size: 16px;
      }
      &.selected {
        background: #ebfeec;
      }
      &.item-disabled {
        cursor: not-allowed;
        background: #fff;
        .package-name,
        .package-unitprice {
          color: #cdcdcd;
        }
      }
    }
  }
  .detail-upload {
    padding-left: 60px;

    .upload-info {
      color: #c0c0c0;
      font-size: 12px;
      .info-icon {
        font-size: 14px;
        margin-right: 4px;
      }
    }
  }
  :deep(.ant-form-item-label) {
    font-weight: 600;
    & > label {
      font-size: 12px;
      color: #192236;
    }
  }
  .none-handle {
    :deep(.ant-input-number-handler-wrap) {
      display: none;
    }
  }
}
</style>
